from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional

from db.session import get_db
from schemas.execution_record import ExecutionRecord, ExecutionRecordCreate, ExecutionRecordUpdate
from crud.record import ExecutionRecordService

router = APIRouter(
    prefix="/records",
    tags=["records"]
)

@router.get("/{record_id}", response_model=ExecutionRecord)
def get_execution_record(record_id: str, db: Session = Depends(get_db)):
    db_record = ExecutionRecordService.get_execution_record(db, record_id)
    if db_record is None:
        raise HTTPException(status_code=404, detail="Execution record not found")
    return db_record

@router.get("/", response_model=List[ExecutionRecord])
def get_execution_records(
    skip: int = 0, 
    limit: int = 100, 
    task_id: Optional[str] = None,
    db: Session = Depends(get_db)
):
    records = ExecutionRecordService.get_execution_records(
        db, 
        skip=skip, 
        limit=limit,
        task_id=task_id
    )
    return records

@router.post("/", response_model=ExecutionRecord)
def create_execution_record(record: ExecutionRecordCreate, db: Session = Depends(get_db)):
    return ExecutionRecordService.create_execution_record(db, record)

@router.put("/{record_id}", response_model=ExecutionRecord)
def update_execution_record(
    record_id: str, 
    record: ExecutionRecordUpdate, 
    db: Session = Depends(get_db)
):
    db_record = ExecutionRecordService.update_execution_record(db, record_id, record)
    if db_record is None:
        raise HTTPException(status_code=404, detail="Execution record not found")
    return db_record

@router.delete("/{record_id}")
def delete_execution_record(record_id: str, db: Session = Depends(get_db)):
    success = ExecutionRecordService.delete_execution_record(db, record_id)
    if not success:
        raise HTTPException(status_code=404, detail="Execution record not found")
    return {"message": "Execution record deleted successfully"} 